pipeline {
    agent any
    environment {
        // 配置变量
        GIT_REPO = '仓库地址'
        GIT_BRANCH = '拉取哪个分支'
        GIT_CREDENTIALS = 'jenkins配置的git账号密码'
        JDK_HOME = '服务器上的JDK地址'
        MAVEN_HOME = '服务器上的maven地址'
        # maven编译脚本: -DskipTests=true:跳过测试 -P prod:指定生产环境打包，其他自行百度
        MAVEN_OPTS = '-DskipTests=true -P prod'
        # JVM参数，根据服务器内存调整，一般为服务器内存的一半
        JVM_OPTS = '-Xmx1024m -Xms512m'
        # docker-compose.yml文件路径
        DOCKER_COMPOSE_FILE = 'docker-compose.yml'
        # 构建成功发送邮件通知的邮箱
        EMAIL_TO = '接受通知的邮箱'
    }
    stages {
        stage('设置工作目录') {
            steps {
                dir('workspace') {
                    deleteDir()
                }
            }
        }
        stage('拉取代码') {
            steps {
                git branch: "${GIT_BRANCH}", credentialsId: "${GIT_CREDENTIALS}", url: "${GIT_REPO}"
            }
        }
        stage('编译打包') {
            steps {
                withEnv(["JAVA_HOME=${JDK_HOME}", "MAVEN_HOME=${MAVEN_HOME}"]) {
                    sh "${MAVEN_HOME}/bin/mvn clean package ${MAVEN_OPTS} -DargLine='${JVM_OPTS}'"
                }
            }
        }
        stage('清理旧容器') {
            steps {
                sh "docker-compose -f ${DOCKER_COMPOSE_FILE} down"
            }
        }
        stage('构建并启动容器') {
            steps {
                sh "docker-compose -f ${DOCKER_COMPOSE_FILE} up -d --build"
            }
        }
        stage('输出构建信息') {
            steps {
                script {
                    def buildTime = currentBuild.durationString
                    echo "构建用时: ${buildTime}"
                    echo "构建完成"
                }
            }
        }
        stage('发送邮件通知') {
            steps {
                script {
                    if (params.SEND_EMAIL == 'true') {
                        emailext body: '构建已完成，请查看构建结果。', subject: '构建通知', to: "${EMAIL_TO}"
                    }
                }
            }
        }
    }
    post {
        success {
            echo '构建成功'
        }
        failure {
            echo '构建失败'
        }
    }
}